package frame.Good;

import MyBatis.MyBatislianjian;
import frame.GuanliPanel;
import org.apache.ibatis.session.SqlSession;
import org.example.mapper.GoodMapper;
import org.example.pojo.Good;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class goodupdate extends JInternalFrame {
    private JTable table;
    private DefaultTableModel tableModel;
    private SqlSession sqlSession = MyBatislianjian.getSqlSession();
    private GoodMapper goodMapper = sqlSession.getMapper(GoodMapper.class);

    public goodupdate() {
        // 设置内部窗口的标题和关闭方式
        setTitle("修改商品信息");
        setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);

        // 创建表格模型和表格
        tableModel = new DefaultTableModel();
        table = new JTable(tableModel);

        // 添加表头
        String[] columnNames = {"商品编号", "商品名称", "商品价格", "客户编号", "商品介绍", "备注"};
        tableModel.setColumnIdentifiers(columnNames);

        // 初始化表格数据
        initializeTableData();

        // 将表格及其滚动面板添加到中心区域
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        // 创建按钮面板并添加到 SOUTH 区域
        JPanel buttonPanel = new JPanel();
        JButton updateButton = new JButton("确定修改");
        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateGoods(); // 点击确定修改按钮时执行更新操作
            }
        });
        JButton returnButton = new JButton("返回");
        returnButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GuanliPanel.setContent(new GoodPanel());
            }
        });
        buttonPanel.add(updateButton);
        buttonPanel.add(returnButton);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);

        // 设置内部窗口的大小和可见性
        setSize(800, 600);
        setVisible(true);
    }

    // 初始化表格数据
    private void initializeTableData() {
        List<Good> goods = goodMapper.selectAll();

        // 清除现有数据
        tableModel.setRowCount(0);

        // 添加新的数据
        for (Good good : goods) {
            tableModel.addRow(new Object[]{
                    good.getGid(),
                    good.getGName(),
                    good.getGPay(),
                    good.getCid(),
                    good.getGIntroduction(),
                    good.getOther()
            });
        }
    }

    // 更新商品信息到数据库
// 更新商品信息到数据库
    private void updateGoods() {
        int rowCount = table.getRowCount();
        boolean hasChanges = false; // 检查是否有任何数据变化

        for (int row = 0; row < rowCount; row++) {
            String gid = ((String) table.getValueAt(row, 0)).trim();
            String gName = ((String) table.getValueAt(row, 1)).trim();
            Float value = (Float) table.getValueAt(row, 2);
            String gPayStr = String.valueOf(value).trim();
            String cid = ((String) table.getValueAt(row, 3)).trim();
            String gIntroduction = ((String) table.getValueAt(row, 4)).trim();
            String other = ((String) table.getValueAt(row, 5)).trim();

            Float gPay = null;
            try {
                if (!gPayStr.isEmpty()) {
                    gPay = Float.parseFloat(gPayStr);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "商品价格字段必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 检查关键字段不能为空字符
            if (gid.isEmpty() || gName.isEmpty() || cid.isEmpty()) {
                JOptionPane.showMessageDialog(this, "每一行的商品编号、商品名称、客户编号都不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 获取原始数据
            Good originalGood = goodMapper.selectGoodById(gid);
            if (originalGood != null) {
                // 检查数据是否有变化
                if (!originalGood.getGName().equals(gName)
                        || !originalGood.getCid().equals(cid)
                        || !originalGood.getGIntroduction().equals(gIntroduction)
                        || !originalGood.getOther().equals(other)
                        || !isEqual(originalGood.getGPay(), gPay)) {
                    // 更新数据库中的商品信息
                    Good updatedGood = new Good(gid, gName, gPay, cid, gIntroduction, other);
                    goodMapper.updateGood(updatedGood);
                    hasChanges = true; // 标记有变化
                }
            }
        }

        if (hasChanges) {
            JOptionPane.showMessageDialog(this, "商品信息已更新！", "提示", JOptionPane.INFORMATION_MESSAGE);
            // 刷新表格数据
            refreshTableData();
        } else {
            JOptionPane.showMessageDialog(this, "没有检测到任何更改。", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    // 检查两个 float 类型的值是否相等（处理 null 的情况）
    private boolean isEqual(Float f1, Float f2) {
        if (f1 == null && f2 == null) {
            return true;
        }
        if (f1 == null || f2 == null) {
            return false;
        }
        return Float.compare(f1, f2) == 0;
    }


    // 刷新表格数据的方法
    private void refreshTableData() {
        List<Good> goods = goodMapper.selectAll();

        // 清除现有数据
        tableModel.setRowCount(0);

        // 添加新的数据
        for (Good good : goods) {
            tableModel.addRow(new Object[]{
                    good.getGid(),
                    good.getGName(),
                    good.getGPay(),
                    good.getCid(),
                    good.getGIntroduction(),
                    good.getOther()
            });
        }
    }
}
